from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from utils.ResultModel import ResultModel
import urllib.request
import json
from string import Template


# Create your views here.
baseUrl = "https://api.bilibili.com"

url = {
    # mid=
    "userInfo": Template("/x/space/acc/info?mid=${mid}"),
    # ?dynamic_id=&offset=
    "dynamic": Template("https://api.live.bilibili.com/dynamic_repost/v1/dynamic_repost/view_repost?dynamic_id=${dynamic_id}&offset=${offset}"),

    # vmid=
    "stat": Template("/x/relation/stat?vmid=${vmid}"),
}
header = {
        # 浏览器的版本
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36"
}


def getUserInfo(request):
    mid = request.GET.get("mid")
    req = urllib.request.Request(baseUrl + url["userInfo"].substitute(mid=mid), headers=header)
    res = urllib.request.urlopen(req)
    data_json = json.loads(res.read().decode('utf-8'))["data"]
    return ResultModel.success(data_json)


def getUserStat(request):
    vmid = request.GET.get("vmid")
    req = urllib.request.Request(baseUrl + url["stat"].substitute(vmid=vmid), headers=header)
    res = urllib.request.urlopen(req)
    data_json = json.loads(res.read().decode('utf-8'))["data"]
    return ResultModel.success(data_json)


def getDynamicInfo(request):
    dynamic_id = request.GET.get("dynamic_id")
    offset = request.GET.get("offset")
    req = urllib.request.Request(url["dynamic"].substitute(dynamic_id=dynamic_id, offset=offset), headers=header)
    print(url["dynamic"].substitute(dynamic_id=dynamic_id, offset=offset))
    res = urllib.request.urlopen(req)
    return ResultModel.success(res.read().decode('utf-8'))
